package com.lyw.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyw.blog.common.exception.BlogException;
import com.lyw.blog.common.util.BeanTransUtils;
import com.lyw.blog.common.util.JwtUtils;
import com.lyw.blog.common.util.SecurityUtil;
import com.lyw.blog.mapper.UserInfoMapper;
import com.lyw.blog.pojo.dataobject.BlogInfo;
import com.lyw.blog.pojo.dataobject.UserInfo;
import com.lyw.blog.pojo.request.UserLoginRequest;
import com.lyw.blog.pojo.response.UserInfoResponse;
import com.lyw.blog.pojo.response.UserLoginResponse;
import com.lyw.blog.service.BlogService;
import com.lyw.blog.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource(name = "blogServiceImpl")
    private BlogService blogService;
    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getUserName, userLoginRequest.getUserName())
                .eq(UserInfo::getDeleteFlag, 0);
        //查询数据库
        //TODO 添加try catch
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (userInfo == null){
            //用户不存在
            throw new BlogException("用户不存在");
        }
        //判断密码是否正确
//        if (!userLoginRequest.getPassword().equals(userInfo.getPassword())){
//            throw new BlogException("用户密码错误");
//        }
        if (!SecurityUtil.verify(userLoginRequest.getPassword(), userInfo.getPassword())){
            throw new BlogException("用户密码错误");
        }
        //密码正确
        Map<String, Object> map = new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("name", userInfo.getUserName());
        String token = JwtUtils.genToken(map);
        return new UserLoginResponse(userInfo.getId(), token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getDeleteFlag, 0)
                .eq(UserInfo::getId, userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return BeanTransUtils.trans(userInfo);
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        //1. 根据blogId 获取博客信息(包含作者ID)
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if (blogInfo==null || blogInfo.getUserId()<=0){
            throw new BlogException("博客不存在");
        }
        //2. 根据作者ID, 获取作者信息
        return getUserInfo(blogInfo.getUserId());
    }
}
